package com.example.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 网关过滤器
 */
public class TokenCheckGateWayFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String url = exchange.getRequest().getPath().pathWithinApplication().value();
        System.out.println("请求URL:" + url);
        System.out.println("method:" + exchange.getRequest().getMethod());

        //获取param 请求参数
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        System.out.println("uname：" + uname);
        //获取header
        String token = exchange.getRequest().getHeaders().getFirst("token");
        System.out.println("token：" + token);

        if (StringUtils.isBlank(token))
        {
            System.out.println("*****头部验证不通过，请在头部输入  token");
            //终止请求，直接回应
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
